import { instance } from './http';
import { isString } from 'lodash';
import type { AxiosRequestConfig } from 'axios';
import router from '@/routes';
import {Response} from '@/type'

const putUrl: (url: string) => string = (url) => {
  if (url.startsWith('/')) {
    return putUrl(url.substring(1));
  }
  return url;
};

const getUrl = (url:any) => {
  let requestUrl = `${url}`;
  if (!isString(url)) {
    requestUrl = `${url.context ?? ''}`;
  }
  return `/${putUrl(requestUrl)}`;
};

/**
 * 请求
 * @param url 请求路径
 * @param options 请求设置
 */
const request = async <T = any>(url: any, options?: any) => {
  try {
    const targetUrl = getUrl(url);

    return instance
      .request<any>({
        url: targetUrl,
        ...(options || {}),
      })
      .then((rs) => {
        if (!rs) {
          throw new Error('没响应');
        }
        if (isString(rs)) {
          // 处理字符串类型的数据
          return {
            success: false,
            message: rs,
          };
        }
        return rs
          ? Promise.resolve<Response<T>>(rs as any)
          : Promise.reject<Response<T>>({
              success: false,
              message:'没响应',
            });
      });
  } catch (error) {
    return Promise.resolve<Response<T>>({ success: false, message: `${error}` });
  }
};

/**
 * GET 请求
 * @param url 请求路径
 * @param options 请求设置
 */
const getRequest = <T = any>(url: string, options?: AxiosRequestConfig) =>
  request<T>(getUrl(url), { ...options, method: 'GET' });

/**
 * POST 请求
 * @param url 请求路径
 * @param options 请求设置
 */
const postRequest = <T = any>(url: string, options?: AxiosRequestConfig) =>
  request<T>(getUrl(url), { ...options, method: 'POST' });

/**
 * PUT 请求
 * @param url 请求路径
 * @param options 请求设置
 */
const putRequest = <T = any>(url: string, options?: AxiosRequestConfig) =>
  request<T>(getUrl(url), { ...options, method: 'PUT' });

/**
 * DELETE 请求
 * @param url 请求路径
 * @param options 请求设置
 */
const deleteRequest = <T = any>(url: string, options?: any) =>
  request<T>(getUrl(url), { ...options, method: 'DELETE' });

export { request, getRequest, postRequest, putRequest, deleteRequest };

